package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XuChengException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.mapper.CourseMapperStruct;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author luhao
 */
@Slf4j
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {
    @Autowired
    private CourseMapperStruct courseMapperStruct;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;
    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Override
    public PageResult<CourseBase> queryByPage(PageParams pageParams, QueryCourseParamsDto dto) {
        // 设置分页信息
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        // 设置查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(dto.getAuditStatus()), CourseBase::getAuditStatus, dto.getAuditStatus())
                .eq(StringUtils.isNotEmpty(dto.getPublishStatus()), CourseBase::getStatus, dto.getPublishStatus())
                .like(StringUtils.isNotEmpty(dto.getCourseName()), CourseBase::getName, dto.getCourseName());
        this.baseMapper.selectPage(page, queryWrapper);
        // 获取条目数
        List<CourseBase> records = page.getRecords();
        // 获取总数
        long total = page.getTotal();
        long current = page.getCurrent();
        long size = page.getSize();
        PageResult<CourseBase> pageResult = new PageResult<>(records, total, current, size);
        return pageResult;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto addCourseInfo(Long companyId, AddCourseDto addCourseDto) {
        // 服务层要对传输的数据进行业务逻辑校验，数据校验再controller进行
        if (companyId == null) {
            XuChengException.cast("机构id为空");
        }
        // 从dto中获取课程基本信息保存到CourseBase表中
        CourseBase courseBase = courseMapperStruct.toCourseBase(addCourseDto);
        courseBase.setCompanyId(companyId);
        courseBase.setCreateDate(LocalDateTime.now(ZoneId.of("+8")));
        // 设置默认课程状态
        courseBase.setStatus("002002");
        // 设置默认审核状态
        courseBase.setAuditStatus("202002");
        if (this.baseMapper.insert(courseBase) <= 0){
            XuChengException.cast("添加课程基础信息失败");
        }
        // dto获取营销信息保存到CourseMarket表中
        // 获取添加课程id
        Long id = courseBase.getId();
        CourseMarket courseMarket = courseMapperStruct.toCourseMarket(addCourseDto);
        courseMarket.setId(id);
        if("201001".equals(courseMarket.getCharge())){
            if (courseMarket.getPrice() == null || courseMarket.getOriginalPrice() == null) {
                XuChengException.cast("收费课程价格不能为空");
            }
        }
        if (courseMarketMapper.insert(courseMarket) <= 0) {
            XuChengException.cast("添加课程营销信息失败");
        }
        // 查询课程基础信息和营销信息返回给前端
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(id);
        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto queryCourseById(Long courseId) {
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(courseId);
        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto amendCourseInfo(Long companyId,EditCourseDto courseDto) {
        // 转换成课程基础信息
        CourseBase courseBase = courseMapperStruct.toCourseBase(courseDto);
        courseBase.setId(courseDto.getId());
        if (!companyId.equals(courseDto.getCompanyId())) {
            XuChengException.cast("机构不同无法修改课程信息");
        }
        courseBase.setChangeDate(LocalDateTime.now());
        int updateCourseBaseById = this.baseMapper.updateById(courseBase);
        if (updateCourseBaseById <= 0) {
            XuChengException.cast("修改课程基础信息失败");
        }
        // 转换成课程营销信息
        CourseMarket courseMarket = courseMapperStruct.toCourseMarket(courseDto);
        courseMarket.setId(courseDto.getId());
        int updateCourseMarketById = courseMarketMapper.updateById(courseMarket);
        if (updateCourseMarketById <= 0){
            XuChengException.cast("修改课程营销信息息失败");
        }
        // 转换成课程分类信息
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(courseDto.getId());
        return courseBaseInfoDto;
    }

    @Override
    @Transactional
    public boolean removeCourseInfo(Long companyId, Long courseId) {
        // 根据课程id查询出课程基础信息
        CourseBase courseBase = baseMapper.selectById(courseId);
        if (!courseBase.getAuditStatus().equals("202002")) {
            XuChengException.cast("课程状态非未提交状态，无法删除");
        }
        if (!courseBase.getCompanyId().equals(companyId)) {
            XuChengException.cast("其他机构无法删除本机构课程信息");
        }
        // 删除课程营销信息
        int deleteCourseMarket = courseMarketMapper.deleteById(courseBase.getId());
        // 删除课程计划和媒资信息
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teachplan::getCourseId, courseId);
        teachplanMapper.delete(wrapper);
        // 删除课程媒资信息
        LambdaQueryWrapper<TeachplanMedia> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TeachplanMedia::getCourseId, courseId);
        teachplanMediaMapper.delete(lambdaQueryWrapper);
        // 删除课程计划老师
        LambdaQueryWrapper<CourseTeacher> courseTeacherWrapper = new LambdaQueryWrapper<>();
        courseTeacherWrapper.eq(CourseTeacher::getCourseId, courseId);
        courseTeacherMapper.delete(courseTeacherWrapper);
        // 删除课程信息
        baseMapper.deleteById(courseId);
        return true;
    }

    private CourseBaseInfoDto getCourseBaseInfoDto(Long id) {
        CourseBase queryCourseBase = this.baseMapper.selectById(id);
        CourseMarket querytCourseMarket = courseMarketMapper.selectById(id);
        if (querytCourseMarket == null || querytCourseMarket == null) {
            XuChengException.cast("查询课程信息为空");
        }
        // 封装课程信息
        CourseBaseInfoDto courseBaseInfoDto = courseMapperStruct.toCourseBaseInfoDto(queryCourseBase, querytCourseMarket);
        // 查询课程分类名称信息
        CourseCategory mt = courseCategoryMapper.selectById(queryCourseBase.getMt());
        CourseCategory st = courseCategoryMapper.selectById(queryCourseBase.getSt());
        if (mt == null || st == null) {
            XuChengException.cast("查询课程分类信息名称为空");
        }
        courseBaseInfoDto.setMtName(mt.getName());
        courseBaseInfoDto.setStName(st.getName());
        return courseBaseInfoDto;
    }
}
